"""Routes configuration

The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
"""
from pylons import config
from routes import Mapper
from routes.util import controller_scan

import logging
log = logging.getLogger(__name__)


def find_controllers():
    #local_controllers = controller_scan(config['pylons.paths']['controllers'])
    controllers = config['mtp.controllers'].keys()
    log.debug('all controllers = %s' % str(controllers))
    return controllers


class MTPMapper(Mapper):
    def _prefixConnect(self, prefix, *args, **kwargs):
        args = list(args)
        idx = 1 if len(args) == 2 else 0
        
        args[idx] = prefix + args[idx]
        return Mapper.connect(self, *args, **kwargs)

    def _prefixResource(self, prefix, *args, **kwargs):
        kwargs['path_prefix'] = prefix + kwargs.get('path_prefix', '')
        Mapper.resource(self, *args, **kwargs)

    def pageConnect(self, *args, **kwargs):
        return self._prefixConnect('pages/:page_id/', *args, **kwargs)

    def pageResource(self, *args, **kwargs):
        kwargs['parent_resource'] = dict(member_name='page', collection_name='pages')
        return Mapper.resource(self, *args, **kwargs)

    def searchConnect(self, *args, **kwargs):
        return self._prefixConnect('search/', *args, **kwargs)

    def configConnect(self, *args, **kwargs):
        return self._prefixConnect('config/', *args, **kwargs)

    def configResource(self, *args, **kwargs):
        return self._prefixResource('config/', *args, **kwargs)


def make_map():
    """Create, configure and return the routes Mapper"""
    #map = Mapper(directory=config['pylons.paths']['controllers'],
    #             always_scan=config['debug'])
    map = MTPMapper(controller_scan=find_controllers,
                 always_scan=config['debug'])

    # The ErrorController route (handles 404/500 error pages); it should
    # likely stay at the top, ensuring it can always be resolved
    #map.connect('error/:action/:id', controller='error')

    # CUSTOM ROUTES HERE

    map.resource('page', 'pages', 
        new={
            'preview': 'POST',
        },
        #parent_resource=dict(member_name='workspace', collection_name='workspaces'),
    )

    map.connect('home', '', controller='pages', 
        action='show', 
        id='Index', 
    )

    map.connect('css/mtp.css', controller='css', action='get')
    map.connect('config', 'config', controller='config', action='index')

    #map.connect('', controller='pages', action='show', id='index')
    #map.connect(':controller/:action/:id')
    #map.connect('*url', controller='template', action='view')

    return map


